<template>
  <CollapsibleSection
    title="主诉"
    :is-expanded="isExpanded"
    @toggle="$emit('toggle')"
  >

    <!-- 选择医院和科室按钮 -->
    <view class="hospital-selector" @click="showDirectoryPopup">
      <view class="selector-content">
        <text class="selector-text">
          {{ getSelectorText() }}
          <!-- 点击选择MDT  -->
        </text>
        <text class="selector-arrow">▼</text>
      </view>
    </view>

    <!-- 下拉选择疾病 -->
    <view class="disease-selector mb-2" @click="showDiseasePopupHandler">
      <view class="selector-content">
        <text class="selector-text">
          {{ getDiseaseSelectorText() }}
        </text>
        <text class="selector-arrow">▼</text>
      </view>
    </view>
    
    <!-- 使用新的医院-部门-科室-项目组选择器 -->
    <HospitalDepartmentProjectSelector
      :visible="showPopup"
      @update:visible="showPopup = $event"
      @close="closeDirectoryPopup"
      @confirm="handleSelectorConfirm"
    />

    <!-- 疾病选择弹窗 -->
    <DiseaseSelector
      :visible="showDiseasePopup"
      :project-id="(formData as any).projectId"
      @update:visible="showDiseasePopup = $event"
      @close="closeDiseasePopup"
      @confirm="handleDiseaseConfirm"
    />

    <ItemWithImagesCard
      :model-value="{ title: '', description: formData.chiefComplaint || '', images: formData.chiefComplaintImages || [] }"
      @update:model-value="(data) => { updateField('chiefComplaint', data.description); if (data.images?.length) updateField('chiefComplaintImages', data.images); }"
      :show-title="true"
      title-label="主诉"
      title-placeholder="病症病情"
      description-label="主诉症状"
      description-placeholder="主诉核心结构，症状 + 部位 + 时间"
      :description-rows="3"
      border-color="border-purple-300"
    />

    <!-- 新增自定义疾病项目 -->
    <view class="new-disease-items-section">
      <view class="section-divider">
        <text class="divider-text">或添加自定义疾病</text>
      </view>
      
      <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
        <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增疾病项目</text>
        <ItemWithImagesCard
          v-for="(_item, index) in newDiseaseItems"
          :key="index"
          v-model="newDiseaseItems[index]"
          :show-delete="true"
          title-label="疾病名称"
          description-label="疾病描述"
          :description-rows="2"
          border-color="border-blue-300"
          @delete="removeNewDiseaseItem(index)"
          class="mb-[16rpx]"
        />
        <nut-button type="success" size="small" @click="addNewDiseaseItem" class="w-full"> 添加新疾病项目 </nut-button>
      </view>
    </view>
  </CollapsibleSection>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useMedicalRecordStore } from '@/store/modules'
import CollapsibleSection from '@/components/CollapsibleSection.vue'
import ItemWithImagesCard from '@/components/ItemWithImagesCard.vue'
import HospitalDepartmentProjectSelector from '@/components/HospitalDepartmentProjectSelector.vue'
import DiseaseSelector from '@/components/DiseaseSelector.vue'

interface Props {
  isExpanded: boolean
}

interface Emits {
  (e: 'toggle'): void
}


defineProps<Props>()
defineEmits<Emits>()

const medicalRecordStore = useMedicalRecordStore()

const formData = computed(() => {
  const storeData = medicalRecordStore.getData
  if (storeData) {
    return storeData
  }
  return medicalRecordStore.getDefaultFormData()
})

const updateField = (field: string, value: any) => {
  console.log("更新字段:", field, value)
  medicalRecordStore.updateField(field as any, value)
}

// 获取选择器显示文本
const getSelectorText = () => {
  const parts: string[] = []
  if (formData.value.hospital) parts.push(formData.value.hospital)
  if (formData.value.department) parts.push(formData.value.department)
  if (formData.value.dept) parts.push(formData.value.dept)
  if (formData.value.project) parts.push(formData.value.project)
  
  if (parts.length) {
    return parts.join(' / ')
  }
  return '请选择机构/部门/科室/项目组'
}

// 选择器弹窗状态与处理
const showPopup = ref(false)
const showDirectoryPopup = () => {
  showPopup.value = true
}
const closeDirectoryPopup = () => {
  showPopup.value = false
}
const handleSelectorConfirm = (data: any) => {
  const { hospital, team, department, project } = data
  if (hospital) updateField('hospital', hospital.title || hospital.name)
  if (team) updateField('department', team.title || team.name)
  if (department) updateField('dept', department.title || department.name)
  if (project) {
    updateField('project', project.title || project.name)
    // 保存项目组ID用于疾病查询
    updateField('projectId', project.id || project.key)
  }
  showPopup.value = false
}

// 疾病选择相关状态
const showDiseasePopup = ref(false)

// 新增疾病项目相关状态
const newDiseaseItems = ref<any[]>([
  {
    title: '',
    description: '',
    images: []
  }
])

// 疾病选择器相关方法
const showDiseasePopupHandler = () => {
  showDiseasePopup.value = true
}

const closeDiseasePopup = () => {
  showDiseasePopup.value = false
}

// 处理疾病选择确认
const handleDiseaseConfirm = (disease: any) => {
  if (disease.customItems) {
    // 处理自定义项目
    const customDiseaseName = disease.customItems.map((item: any) => item.title).join('、')
    updateField('disease', customDiseaseName)
    updateField('diseaseId', disease.id)
    updateField('customDiseaseItems', disease.customItems)
  } else {
    // 处理标准疾病
    updateField('disease', disease.name)
    updateField('diseaseId', disease.id)
  }
}

// 获取疾病选择器显示文本
const getDiseaseSelectorText = () => {
  if ((formData.value as any).disease) {
    return (formData.value as any).disease
  }
  return '请选择疾病（开发中）'
}

// 新增疾病项目相关方法
const addNewDiseaseItem = () => {
  newDiseaseItems.value.push({
    title: '',
    description: '',
    images: []
  })
}

const removeNewDiseaseItem = (index: number) => {
  if (newDiseaseItems.value.length > 1) {
    newDiseaseItems.value.splice(index, 1)
  }
}

// 组件挂载时获取疾病列表
onMounted(() => {
  // fetchDiseaseList()
})
</script>

<style scoped lang="scss">
.hospital-selector {
  border: 1rpx solid #e5e7eb;
  border-radius: 12rpx;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:hover {
    border-color: #3b82f6;
  }
  
  &:active {
    opacity: 0.8;
  }
  
  .selector-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;
    
    .selector-text {
      font-size: 28rpx;
      color: #374151;
      flex: 1;
    }
    
    .selector-arrow {
      font-size: 24rpx;
      color: #9ca3af;
      margin-left: 16rpx;
      transition: transform 0.2s ease;
    }
  }
  
  &:active .selector-arrow {
    transform: rotate(180deg);
  }
}

.disease-selector {
  border: 1rpx solid #e5e7eb;
  border-radius: 12rpx;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-top: 24rpx;
  
  &:hover {
    border-color: #3b82f6;
  }
  
  &:active {
    opacity: 0.8;
  }
  
  .selector-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;
    
    .selector-text {
      font-size: 28rpx;
      color: #374151;
      flex: 1;
    }
    
    .selector-arrow {
      font-size: 24rpx;
      color: #9ca3af;
      margin-left: 16rpx;
      transition: transform 0.2s ease;
    }
  }
  
  &:active .selector-arrow {
    transform: rotate(180deg);
  }
}

// 新增疾病项目区域样式
.new-disease-items-section {
  margin-top: 24rpx;
  
  .section-divider {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    
    &::before,
    &::after {
      content: '';
      flex: 1;
      height: 1rpx;
      background: #e0e0e0;
    }
    
    .divider-text {
      padding: 0 24rpx;
      font-size: 24rpx;
      color: #666;
      background: white;
    }
  }
}

</style>
